package com.supersoul.myself.service.impl;

import com.supersoul.myself.dao.CommentDao;
import com.supersoul.myself.dao.UserDao;
import com.supersoul.myself.entity.Comment;
import com.supersoul.myself.entity.User;
import com.supersoul.myself.enums.ScoreEnum;
import com.supersoul.myself.ex.ServiceException;
import com.supersoul.myself.service.CommentService;
import com.supersoul.myself.util.PageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private UserDao userDao;

    @Override
    public String saveComment(Comment comment, User user) throws ServiceException {
        comment.buildCreate();
        comment.setCreatorId(user.getId());
        comment.setCreatorName(user.getUserName());
        commentDao.save(comment);
        user.setScore(user.getScore() + ScoreEnum.PUBLISH_COMMENT.getScore());
        userDao.save(user);
        return comment.getId();
    }


    @Override
    public Page<Comment> getBlog(String blogId, PageVO pageVO) throws ServiceException {
        List<Sort.Order> orderList = new ArrayList<>();
        orderList.add(new Sort.Order(Sort.Direction.DESC, "createTime"));
        Pageable pageable = PageRequest.of(pageVO.getPageNum(), pageVO.getPageSize(), Sort.by(orderList));
        // 对博客的评论
        Page<Comment> commentPage = commentDao.findByBlogIdAndReplyIdIsNull(blogId, pageable);
        List<Comment> commentList = commentPage.getContent();
        // 对评论的评论
        if (!CollectionUtils.isEmpty(commentList)) {
            for (Comment comment : commentList) {

                List<Comment> replyList = commentDao.findByReplyRootId(comment.getId(), Sort.by(orderList));
                comment.setReplyList(replyList);
            }
        }
        return commentPage;
    }
}
